import { alert, msg, loading, hideAlerts } from '../notice/notice';
import AccountsDialog from './accounts-dialog';
import AccountsSession from './accounts-session';

//
// Define Variable
//

let doneCallback;

//
// On Email Verification Link
//

Accounts.onEmailVerificationLink(function(token, done) {
  Accounts.verifyEmail(token, function(error) {
    if (!error) {
      AccountsSession.set('emailVerificationSuccess', true);
    }

    done();
  });
});

//
// On Reset Password Link
//

Accounts.onResetPasswordLink(function(token, done) {
  AccountsSession.set('resetPasswordToken', token);
  doneCallback = done;
});

//
// Get Value
//

let getValueById = function(id) {
  let element = document.getElementById(id);
  if (!element) 
    return null;
  else 
    return element.value;
};

let getTrimmedValueById = function(id) {
  let element = document.getElementById(id);
  if (!element) 
    return null;
  else 
    return element.value.replace(/^\s*|\s*$/g, '');
};

let getTrimmedAllValueById = function(id) {
  let element = document.getElementById(id);
  if (!element) 
    return null;
  else 
    return element.value.replace(/\s/g, '');
};

//
// Validate Value
//

let validateEmail = function(email) {
  let email_regexp = /^[a-z0-9_\.\-]*@[a-z0-9\.\-]+\.[a-z]{2,4}$/i;

  if (email_regexp.test(email)) {
    return true;
  } else {
    AccountsSession.errorMessage('请输入正确的邮箱');
    return false;
  }
};

let validatePassword = function(password) {
  if (!password) {
    AccountsSession.errorMessage('请输入密码');
    return false;
  }

  if (password.length >= 6) {
    return true;
  } else {
    AccountsSession.errorMessage('密码至少大于6位');
    return false;
  }
};

let validateUsername = function(username) {
  let username_regexp = /^[a-zA-Z0-9_]{3,18}$/;

  if (username_regexp.test(username)) {
    return true;
  } else {
    AccountsSession.errorMessage('请输入正确的用户名');
    return false;
  }
};

//
// Accounts Helper Function
//

let loginValidateEmail = function() {
  let email = getTrimmedAllValueById('loginEmail');

  if (validateEmail(email)) {
    Meteor.call('validateJustEmail', email, function(error, result) {
      if (result) {
        AccountsSession.set('loginValidatedEmail', true);
        $('#loginEmail')
          .attr('readonly', 'readonly')
          .removeClass('form-control')
          .addClass('form-control-plaintext');
        AccountsSession.resetMessage();
      } else {
        AccountsSession.errorMessage(error.reason);
      }
    });
  }
};

let login = function() {
  let email = getValueById('loginEmail');
  let password = getValueById('loginPassword');

  if (validatePassword(password)) {
    Meteor.loginWithPassword(email, password, function(error, result) {
      if (error) {
        AccountsSession.errorMessage('密码错误' || '未知的错误');
      } else {
        toPage();
      }
    });
  }
};

let register = function() {
  let email = getTrimmedAllValueById('registerEmail');
  let password = getValueById('registerPassword');
  let username = getTrimmedValueById('registerUsername');

  let options = {
    email: email,
    password: password,
    username: username
  };

  if (validateEmail(email) && validatePassword(password) && validateUsername(username)) {
    Accounts.createUser(options, function(error) {
      if (error) {
        if (error.reason.indexOf('Email') != -1) {
          AccountsSession.errorMessage('邮箱已存在，请重新输入');
        }

        if (error.reason.indexOf('Username') != -1) {
          AccountsSession.errorMessage('用户名已存在，请重新输入');
        }
      } else {
        sendVerificationEmail(toPage);
        msg({content: '欢迎加入卡司群聊！'});
      }
    });
  }
};

let sendForgotPasswordEmail = function() {
  let email = getTrimmedAllValueById('forgotPasswordEmail');

  if (email != null && validateEmail(email)) {
    let options = { email: email };

    AccountsSession.set('inForgoting', true);
    Accounts.forgotPassword(options, function(error, result) {
      AccountsSession.set('inForgoting', false);

      if (error) {
        if (error.reason.indexOf('User not found' != -1)) {
          AccountsSession.errorMessage('用户不存在');
        }
      } else {
        alert({
          target: '#top-alert-field',
          content: '重置密码邮件发送成功，请进入邮箱查看。',
          classes: 'text-center rounded-0 mb-0',
          close: false
        });
        AccountsDialog.remove();
      }
    });
  }
};

let resetPassword = function() {
  let newPassword = getValueById('newPassword');
  let token = AccountsSession.get('resetPasswordToken');

  if (validatePassword(newPassword) || token) {
    Accounts.resetPassword(token, newPassword, function(error) {
      if (error) {
        AccountsSession.errorMessage(error.reason || '未知的错误');
      } else {
        AccountsSession.set('resetPasswordToken', null);
        toPage();
        
        if (doneCallback) {
          doneCallback();
        }
      }
    });
  }
};

let changePassword = function() {
  let oldPassword = getValueById('oldPassword');
  let newPassword = getValueById('newPassword');

  if (validatePassword(oldPassword) && validatePassword(newPassword)) {
    if (oldPassword === newPassword) {
      AccountsSession.errorMessage('新旧密码不能相同');
      return;
    }

    AccountsSession.set('inReseting', true);
    Accounts.changePassword(oldPassword, newPassword, function(error) {
      AccountsSession.set('inReseting', false);
      if (error) {
        AccountsSession.errorMessage(error.reason || '未知的错误');
      } else {
        $('#oldPassword').val('');
        $('#newPassword').val('');
        AccountsSession.clear();
        alert({
          target: '#change-password-alert-field',
          content: '密码修改成功！'
        });
      }
    });
  }
};

let sendVerificationEmail = function(callback) {
  let userId = Meteor.userId();
  Meteor.call('sendVerificationEmail', userId, function(error, result) {
    if (result) {
      callback();
    }
  });
};

let toPage = function(routerName = 'home') {
  AccountsDialog.remove();
  Router.go(routerName);
};

// 
// export
// 

export {
  sendVerificationEmail
};

//
// accounts templates methods
//

Template.registerHelper('emailVerificationSuccess', function() {
  return AccountsSession.get('emailVerificationSuccess');
});

//
// Buttons模板 accounts_buttons Template Methods
//

Template.accounts_buttons.onRendered(function() {
  this.autorun(function() {
    if (AccountsSession.get('resetPasswordToken')) {
      AccountsDialog.show(
        '#accountsButtons',
        'accounts_reset_password'
      );
    }
  });
});

Template.accounts_buttons.events({
  'click #accountsButtons'(event) {
    AccountsDialog.show('#accountsButtons');
  }
});

//
// Links模板 accounts_links Template Methods
//

Template.accounts_links.onRendered(function() {
  this.autorun(() => {
    if (Meteor.user() && !Meteor.user().emails[0].verified) {
      alert({
        target: '#top-alert-field',
        classes: 'text-center rounded-0 mb-0',
        content: `
          你的电子邮件地址还没有验证。请点击我们发送到邮件里的链接。
          <a href='#' class='alert-link' id='resendVerificationEmail'>重新发送</a>
        `,
        close: false,
        linkId: '#resendVerificationEmail',
        linkCallback: sendVerificationEmail,
        hideLink: true
      });
    }

    if (!Meteor.user()) {
      hideAlerts();
    }
  });
});

Template.accounts_links.events({
  'click #accountsLinksLogin'(event) {
    event.preventDefault();
    AccountsDialog.show('#accountsLinksLogin', 'accounts_login');
  },
  'click #accountsLinksRegister'(event) {
    event.preventDefault();
    AccountsDialog.show('#accountsLinksRegister', 'accounts_register');
  }
});

//
// Dialog模板 accounts_dialog Template Methods
//

Template.accounts_dialog.onCreated(function() {
  if (!AccountsSession.get('accountsDialogContent')) {
    AccountsSession.accountsDialogContent();
  }
});

Template.accounts_dialog.onDestroyed(function() {
  AccountsSession.clear();
});

Template.accounts_dialog.helpers({
  accountsDialogContent() {
    return AccountsSession.get('accountsDialogContent');
  }
});

Template.accounts_dialog.events({
  // 界面切换
  'click #gotoRegister'(event, instance) {
    AccountsSession.accountsDialogContent('accounts_register');
  },
  'click #gotoLogin'(event, instance) {
    AccountsSession.accountsDialogContent('accounts_login');
  },
  'click #gotoReset'(event, instance) {
    AccountsSession.accountsDialogContent('accounts_forgot_password');
  }
});

//
// 注册模板 accounts_register Template Methods
//

Template.accounts_register.events({
  'focus #registerUsername'() {
    AccountsSession.infoMessage('3-18位字符，只能包含英文字母，数字，下划线');
  },
  'blur #registerUsername'() {
    AccountsSession.infoMessage(null);
  },
  'keypress #registerEmail, keypress #registerPassword, keypress #registerUsername'(event) {
    if (event.keyCode === 13) {
      register();
    }
  },
  'click #register'() {
    register();
  }
});

//
// 登录模板 accounts_login Template Methods
//

Template.accounts_login.helpers({
  loginValidatedEmail() {
    return AccountsSession.get('loginValidatedEmail');
  }
});

Template.accounts_login.events({
  // 验证登录邮箱
  'keypress #loginEmail'(event) {
    if (event.keyCode === 13) {
      loginValidateEmail();
    }
  },
  'click #checkLoginEmail'() {
    loginValidateEmail();
  },
  // 用户登录
  'keypress #loginPassword'(event) {
    if (event.keyCode === 13) {
      login();
    }
  },
  'click #login'() {
    login();
  },
});

//
// 忘记密码 accounts_forgot_password Template Methods
//

Template.accounts_forgot_password.helpers({
  inForgoting: function() {
    return AccountsSession.get('inForgoting');
  }
});

Template.accounts_forgot_password.events({
  'keypress #forgotPasswordEmail'(event) {
    if (event.keyCode === 13) {
      sendForgotPasswordEmail();
    }
  },
  'click #sendForgotPasswordEmail'() {
    sendForgotPasswordEmail();
  }
});

//
// 重置密码 accounts_reset_password Template Methods
//

Template.accounts_reset_password.events({
  'keypress #newPassword'(event) {
    if (event.keyCode === 13) {
      resetPassword();
    }
  },
  'click #resetPassword'() {
    resetPassword();
  }
});

//
// 修改密码 accounts_change_password Template Methods
//

Template.accounts_change_password.helpers({
  inReseting: function() {
    return AccountsSession.get('inReseting');
  }
});

Template.accounts_change_password.events({
  'keypress #oldPassword, keypress #newPassword'() {
    if (event.keyCode === 13) {
      changePassword();
    }
  },
  'click #resetPassword'() {
    changePassword();
  }
});

//
// 邮箱验证成功 accounts_verify_email Template Methods
//

Template.accounts_verify_email.onDestroyed(function() {
  AccountsSession.set('emailVerificationSuccess', false);
});

//
// Bind message to accounts_message
//

Template.accounts_message.helpers({
  errorMessage: function() {
    return AccountsSession.get('errorMessage');
  }
});

Template.accounts_message.helpers({
  infoMessage: function() {
    return AccountsSession.get('infoMessage');
  }
});
